#include "showticket.h"
#include "ui_showticket.h"


showticket::showticket(const QString& ostation0,const QString& odate0,const QString& destination0,QWidget *parent):
    QWidget(parent),
    ui(new Ui::showticket)
{
    ui->setupUi(this);
    QSqlQuery query;
    query.prepare("SELECT * FROM 余票信息表 WHERE 出发站 = :ostation AND 目的站 = :destination and 出发时间 like :odate ORDER BY 车次号,出发时间 ");
    query.bindValue(":ostation", ostation0);
    query.bindValue(":destination", destination0);
    query.bindValue(":odate", odate0);
    query.exec();
    // 设置列数
    int columnCount = query.record().count();
    ui->tableWidget->setColumnCount(columnCount);
    // 设置表头
    QStringList headers;
    for (int i = 0; i < columnCount; ++i) {
        headers << query.record().fieldName(i);

    }
    ui->tableWidget->setHorizontalHeaderLabels(headers);

    // 循环遍历查询结果，填充数据到表格中
    int rowCount = 0;
    while (query.next()) {
        ui->tableWidget->insertRow(rowCount);

        for (int column = 0; column < columnCount; ++column) {
            QTableWidgetItem* item = new QTableWidgetItem(query.value(column).toString());
            ui->tableWidget->setItem(rowCount, column, item);
        }

        ++rowCount;
    }
    // 获取水平表头对象
    QHeaderView* header = ui->tableWidget->horizontalHeader();
    // 设置最后一列自动拉伸
    header->setStretchLastSection(true);
    header->setSectionResizeMode(QHeaderView::Fixed);
    // 调整列宽以适应内容
    for (int column = 0; column < ui->tableWidget->columnCount()-1; ++column) {
        ui->tableWidget->resizeColumnToContents(column);
    }
    // 设置表格的编辑属性为NoEditTriggers
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableWidget->verticalHeader()->setVisible(false);
QString styleSheet = "QTableWidget { background-color: #ffffff; }"
                     "QTableWidget::item { background-color: #f5f5f5; }"
                     "QTableWidget::item:alternate { background-color: #ffffff; }"
                     "QTableWidget::item:selected { background-color: #ff69b4; }"
                     "QTableWidget::item:hover { background-color: #e0e0e0; }"
                     "QHeaderView::section { background-color: #a8c5ff; color: #ffffff; border: none; }"
                     "QHeaderView::section:hover { background-color: #9bb4ff; }";

ui->tableWidget->setStyleSheet(styleSheet);
 ui->tableWidget->setAlternatingRowColors(true);
 ui->tableWidget->horizontalHeader()->setStyleSheet(styleSheet);
 ui->tableWidget->verticalHeader()->setStyleSheet(styleSheet);


QFont font("黑体", 8);
ui->tableWidget->setFont(font);
ui->tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);

}

showticket::~showticket()
{
    delete ui;
}

void showticket::on_buyButton_clicked()
{
    QList<QTableWidgetItem *> selectedItems = ui->tableWidget->selectedItems();
        // 获取各个单元格的内容
     if (!selectedItems.isEmpty())
       { QString train_number = selectedItems[0]->text();
        QString ttype = selectedItems[1]->text();
        QString odatetime = selectedItems[4]->text();
       QSqlQuery query;
       query.prepare("SELECT 余票张数 FROM 余票信息表 WHERE 出发时间 = :odatetime AND 车次号 = :train_number and 车票种类 = :ttype  ");
       query.bindValue(":ttype", ttype);
       query.bindValue(":train_number", train_number);
       query.bindValue(":odatetime", odatetime);
       query.exec();query.next();
       QString tcount = query.value(0).toString();
                int ticketCount = tcount.toInt();
                if (ticketCount == 0)
                {
                    QMessageBox::information(this, "提示", "车票已售罄");
                }
                else
                {
                    QMessageBox::StandardButton reply;
                    reply = QMessageBox::question(this, "提示", "是否订购", QMessageBox::Yes | QMessageBox::No);
                    if (reply == QMessageBox::Yes) {
                        //进行订票操作

                    QString cnum,snum;
                     QString csum =generate_csnum( train_number,  odatetime, ttype);
                     int splitIndex = 5; // 分割索引位置
                     cnum = csum.left(splitIndex); // 提取索引位置之前的部分
                     snum = csum.right(csum.length() - splitIndex); // 提取索引位置之后的部分
                     snum = QString::number(snum.toInt());//获得车厢号
                     cnum = QString::number(cnum.toInt());//获得座位号

                     //this->hide();
                     infoin* i=new infoin(ttype,train_number,cnum,snum,odatetime);                    
                     i->show();
                     connect(i,SIGNAL(sendsignal()),this,SLOT(update()));//当点击子界面时，调用主界面的reshow()函数




                    }
                    else {
                        // 用户取消订票
                    }
                }}


}

QString showticket:: generate_csnum(QString train_number, QString odatetime,QString ttype)//生成车厢号,座位号
{
    /*1 - 2车厢 硬卧（4座位）
      3车厢     软卧（2座位）
      4 - 6车厢 硬座（6座位）
      站票在硬座车厢，车厢号和座位号都为0  */

    QString c;
    QString cnum,snum;//车厢号，座位号
    cnum = "0";
    snum = "0";
    if (ttype == "硬座")
    {
        QSqlQuery query;
                query.prepare("select 车厢号,座位号 from 退票座位表  where 车厢号>=4 and 车厢号<=6 and 出发时间= :odatetime and 车次号 = :train_number");
                query.bindValue(":train_number", train_number);
                query.bindValue(":odatetime", odatetime);
                query.exec();

        if (query.next())//查询结果不为空
        {
            cnum=query.value(0).toString();
            snum=query.value(1).toString();
            return cnum + "         " + snum;//返回车厢号和座位号
        }
                query.prepare("select 车厢号 from 订票单表  where 车厢号>=4 and 车厢号<=6 and 出发时间= :odatetime and 车次号 = :train_number");
                query.bindValue(":train_number", train_number);
                query.bindValue(":odatetime", odatetime);
                query.exec();

        if (!query.next())//查询结果为空
        {
            cnum = "4";//如果该车票类型对应的车厢都未售出，则获得该车箱的起始车厢号
            snum = '1';//该车箱的第一个座位
             return cnum + "         " + snum;//返回车厢号和座位号
        }
        else//结果不为空
        {
            query.prepare("select max(车厢号) from 订票单表  where 车厢号>=4 and 车厢号<=6 and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.exec();query.next();
            cnum=query.value(0).toString();
            query.prepare("select count(*) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.bindValue(":cnum", cnum);
            query.exec();query.next();
           if(query.value(0).toInt()<6)//该车箱没有坐满
           {

               query.prepare("select max(座位号) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
               query.bindValue(":train_number", train_number);
               query.bindValue(":odatetime", odatetime);
               query.bindValue(":cnum", cnum);
               query.exec();query.next();
               snum=query.value(0).toString();
               int num = snum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               snum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }
        else//该车箱坐满了
            {
               snum="1";
               int num = cnum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               cnum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }

        }

    }
 else if (ttype == "硬卧")
    {
        QSqlQuery query;
                query.prepare("select 车厢号,座位号 from 退票座位表  where 车厢号>=1 and 车厢号<=2 and 出发时间= :odatetime and 车次号 = :train_number");
                query.bindValue(":train_number", train_number);
                query.bindValue(":odatetime", odatetime);
                query.exec();

        if (query.next())//查询结果不为空
        {
            cnum=query.value(0).toString();
            snum=query.value(1).toString();

            return cnum + "         " + snum;//返回车厢号和座位号
        }
                query.prepare("select 车厢号 from 订票单表  where 车厢号>=1 and 车厢号<=2 and 出发时间= :odatetime and 车次号 = :train_number");
                query.bindValue(":train_number", train_number);
                query.bindValue(":odatetime", odatetime);
                query.exec();

        if (!query.next())//查询结果为空
        {
            cnum = "1";//如果该车票类型对应的车厢都未售出，则获得该车箱的起始车厢号
            snum = '1';//该车箱的第一个座位
             return cnum + "         " + snum;//返回车厢号和座位号
        }
        else//结果不为空
        {
            query.prepare("select max(车厢号) from 订票单表  where 车厢号>=1 and 车厢号<=2 and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.exec();query.next();
            cnum=query.value(0).toString();
            query.prepare("select count(*) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.bindValue(":cnum", cnum);
            query.exec();query.next();
           if(query.value(0).toInt()<4)//该车箱没有坐满
           {

               query.prepare("select max(座位号) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
               query.bindValue(":train_number", train_number);
               query.bindValue(":odatetime", odatetime);
               query.bindValue(":cnum", cnum);
               query.exec();query.next();
               snum=query.value(0).toString();
               int num = snum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               snum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }
        else//该车箱坐满了
            {
               snum="1";
               int num = cnum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               cnum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }

        }
    }
    else if (ttype == "软卧")
    {
        QSqlQuery query;
        query.prepare("delete from 退票座位表  where 车厢号=:cnum and 座位号=snum and 出发时间= :odatetime and 车次号 = :train_number");
        query.bindValue(":train_number", train_number);
        query.bindValue(":odatetime", odatetime);
        query.bindValue(":cnum", cnum);
        query.bindValue(":snum", snum);
                query.exec();

        if (query.next())//查询结果不为空
        {
            cnum=query.value(0).toString();
            snum=query.value(1).toString();

            return cnum + "         " + snum;//返回车厢号和座位号
        }
                query.prepare("select 车厢号 from 订票单表  where 车厢号=3  and 出发时间= :odatetime and 车次号 = :train_number");
                query.bindValue(":train_number", train_number);
                query.bindValue(":odatetime", odatetime);
                query.exec();

        if (!query.next())//查询结果为空
        {
            cnum = "3";//如果该车票类型对应的车厢都未售出，则获得该车箱的起始车厢号
            snum = '1';//该车箱的第一个座位
             return cnum + "         " + snum;//返回车厢号和座位号
        }
        else//结果不为空
        {
            query.prepare("select max(车厢号) from 订票单表  where 车厢号=3  and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.exec();query.next();
            cnum=query.value(0).toString();
            query.prepare("select count(*) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
            query.bindValue(":train_number", train_number);
            query.bindValue(":odatetime", odatetime);
            query.bindValue(":cnum", cnum);
            query.exec();query.next();

           if(query.value(0).toInt()<2)//该车箱没有坐满
           {

               query.prepare("select max(座位号) from 订票单表  where 车厢号=:cnum and 出发时间= :odatetime and 车次号 = :train_number");
               query.bindValue(":train_number", train_number);
               query.bindValue(":odatetime", odatetime);
               query.bindValue(":cnum", cnum);
               query.exec();query.next();
               snum=query.value(0).toString();
               int num = snum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               snum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }
        else//该车箱坐满了
            {
               snum="1";
               int num = cnum.toInt();  // 将字符串转换为整数
               num++;  // 增加整数值
               cnum = QString::number(num);  // 将整数转换为字符串
                return cnum + "         " + snum;//返回车厢号和座位号
            }

        }
    }
    else if (ttype == "站票")
        {

            return cnum + "         " + snum;//返回车厢号和座位号，都为0
        }
        return cnum + "         " + snum;
}

void showticket::update()
{
    int rowIndex = ui->tableWidget->currentRow();
    QTableWidgetItem* item = ui->tableWidget->item(rowIndex, 5);  // 第六列索引为5
    int currentValue = item->text().toInt();  // 将文本转换为整数

    int newValue = currentValue - 1;
    item->setText(QString::number(newValue));  // 更新表格中的文本数据

}
void showticket::on_exitButton_clicked()
{
    emit sendsignal();
       this->close();
}
